<template>
  <div class="global-sidebar" v-if="shouldShowSidebar">
    <a @click="toshoppingcart(user.userId)" class="sidebar-item">
      <div class="cart-icon">
        <i class="el-icon-shopping-cart-2"></i>
        <span v-if="cartCount > 0" class="cart-count">{{ cartCount }}</span>
      </div>
      <span>购物车</span>
    </a>
    
    <router-link to="/profile" class="sidebar-item">
      <i class="el-icon-user"></i>
      <span>我的</span>
    </router-link>
    
    <a @click="openCustomerService" class="sidebar-item">
      <i class="el-icon-service"></i>
      <span>客服</span>
    </a>
    
    <a @click="showFeedbackDialog" class="sidebar-item">
      <i class="el-icon-edit"></i>
      <span>反馈</span>
    </a>

    <!-- 客服信息对话框 -->
    <el-dialog
      title="联系客服"
      :visible.sync="customerServiceDialogVisible"
      width="400px"
      :append-to-body="true"
      custom-class="customer-service-dialog">
      <div class="customer-service-content">
        <div class="contact-item">
          <i class="el-icon-phone"></i>
          <div class="contact-info">
            <div class="contact-label">电话咨询</div>
            <div class="contact-value">18460053070</div>
          </div>
          <el-button 
            type="primary" 
            size="small" 
            class="copy-btn"
            @click="copyToClipboard('18460053070')">
            复制
          </el-button>
        </div>
        
        <div class="contact-item">
          <i class="el-icon-chat-dot-round"></i>
          <div class="contact-info">
            <div class="contact-label">微信咨询</div>
            <div class="contact-value">18460053070</div>
          </div>
          <el-button 
            type="success" 
            size="small" 
            class="copy-btn"
            @click="copyToClipboard('18460053070')">
            复制
          </el-button>
        </div>
        
        <div class="contact-item">
          <i class="el-icon-message"></i>
          <div class="contact-info">
            <div class="contact-label">QQ咨询</div>
            <div class="contact-value">2061066455</div>
          </div>
          <el-button 
            type="warning" 
            size="small" 
            class="copy-btn"
            @click="copyToClipboard('2061066455')">
            复制
          </el-button>
        </div>
      </div>
      <div class="service-time">
        <i class="el-icon-time"></i>
        <span>服务时间：周一至周日 9:00-21:00</span>
      </div>
    </el-dialog>

    <!-- 修改反馈对话框 -->
    <el-dialog
      title="意见反馈"
      :visible.sync="feedbackDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :append-to-body="true">
      <el-form :model="feedbackForm" :rules="rules" ref="feedbackForm" label-width="80px">
        <el-form-item label="类型" prop="type">
          <el-select v-model="feedbackForm.type" placeholder="请选择反馈类型">
            <el-option label="功能建议" value="feature"></el-option>
            <el-option label="界面优化" value="ui"></el-option>
            <el-option label="性能问题" value="performance"></el-option>
            <el-option label="操作问题" value="operation"></el-option>
            <el-option label="其他" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="feedbackForm.title" placeholder="请输入反馈标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            type="textarea"
            :rows="4"
            v-model="feedbackForm.content"
            placeholder="请详细描述您的问题或建议">
          </el-input>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="feedback-uploader"
            action="/api/upload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            :limit="3"
            multiple
            :file-list="feedbackForm.images"
            list-type="picture-card">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">支持jpg/png文件，最多3张</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="feedbackForm.contact" placeholder="请留下您的联系方式，方便我们回复您"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="feedbackDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitFeedback" :loading="submitting">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'GlobalSidebar',
  data() {
    return {
      cartCount: 0,
      user: {},
      feedbackDialogVisible: false,
      submitting: false,
      feedbackForm: {
        type: '',
        title: '',
        content: '',
        contact: '',
        images: []
      },
      rules: {
        type: [
          { required: true, message: '请选择反馈类型', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请输入反馈标题', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入反馈内容', trigger: 'blur' },
          { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
        ],
        contact: [
          { required: true, message: '请输入联系方式', trigger: 'blur' }
        ]
      },
      customerServiceDialogVisible: false,
    }
  },
  methods: {
    toshoppingcart(id) {
      // 检查当前路由
      const targetPath = `/mycart/${id}`;
      if (this.$route.path !== targetPath) {
        this.$router.push(targetPath).catch(err => {
          if (err.name !== 'NavigationDuplicated') {
            throw err;
          }
        });
      }
    },
    openCustomerService() {
      this.customerServiceDialogVisible = true;
    },
    copyToClipboard(text) {
      navigator.clipboard.writeText(text).then(() => {
        this.$message({
          message: '复制成功',
          type: 'success',
          duration: 1500
        });
      }).catch(() => {
        this.$message({
          message: '复制失败，请手动复制',
          type: 'error',
          duration: 1500
        });
      });
    },
    showFeedbackDialog() {
      if (!this.user.userId) {
        this.$message.warning('请先登录后再提交反馈');
        return;
      }
      this.feedbackDialogVisible = true;
    },
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('只能上传图片文件！');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB！');
        return false;
      }
      return true;
    },
    handleUploadSuccess(response, file) {
      this.feedbackForm.images.push({
        url: response.data.url,
        name: file.name
      });
    },
    handleUploadError() {
      this.$message.error('图片上传失败，请重试');
    },
    async submitFeedback() {
      try {
        await this.$refs.feedbackForm.validate();
        
        this.submitting = true;
        const response = await this.request.post('/feedback/submit', {
          ...this.feedbackForm,
          userId: this.user.userId,
          createTime: new Date().toISOString()
        });
        
        if (response.code === 1) {
          this.$message.success('感谢您的反馈！');
          this.feedbackDialogVisible = false;
          this.resetForm();
        } else {
          this.$message.error(response.msg || '提交失败，请重试');
        }
      } catch (error) {
        console.error('提交反馈失败:', error);
        this.$message.error('提交失败，请重试');
      } finally {
        this.submitting = false;
      }
    },
    resetForm() {
      this.feedbackForm = {
        type: '',
        title: '',
        content: '',
        contact: '',
        images: []
      };
      if (this.$refs.feedbackForm) {
        this.$refs.feedbackForm.resetFields();
      }
    },
    async loadCartCount() {
      try {
        const response = await this.request.get('/cartitems/getCartList');
        if (response.data.code === 0) {
          this.cartCount = response.data.data.length || 0;
        }
      } catch (error) {
        console.error('Failed to load cart count:', error);
      }
    },
    async loadUserInfo() {
      try {
        const res = await this.request.get("/users/info");
        if (res.code === 1) {
          this.user = res.data;
        }
      } catch (err) {
        console.error('Failed to load user info', err);
      }
    }
  },
  mounted() {
    this.loadUserInfo();
    this.loadCartCount();
    // 每分钟更新一次购物车数量
    setInterval(this.loadCartCount, 60000);
  },
  computed: {
    shouldShowSidebar() {
      const path = this.$route.path;
      // 在登录页面和管理员页面不显示侧边栏
      return !path.includes('/login') && 
             !path.includes('/admin') && 
             !path.includes('/saveuser');
    }
  }
}
</script>

<style scoped>
.global-sidebar {
  position: fixed;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  background: white;
  border-radius: 8px 0 0 8px;
  box-shadow: -2px 2px 12px rgba(0, 0, 0, 0.1);
  padding: 10px;
  z-index: 1000;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.sidebar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #606266;
  text-decoration: none;
  cursor: pointer;
  padding: 8px;
  transition: all 0.3s ease;
  font-size: 12px;
  border-radius: 4px;
  position: relative;
  overflow: hidden;
}

.sidebar-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #409EFF;
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: -1;
}

.sidebar-item:hover::before {
  opacity: 0.1;
}

.sidebar-item:hover {
  color: #409EFF;
  transform: translateX(-2px);
}

.sidebar-item i {
  font-size: 20px;
  margin-bottom: 4px;
  transition: transform 0.3s ease;
}

.sidebar-item:hover i {
  transform: scale(1.1);
}

.cart-icon {
  position: relative;
  display: inline-block;
}

.cart-count {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #f56c6c;
  color: white;
  border-radius: 10px;
  padding: 0 6px;
  font-size: 12px;
  min-width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;
  transform: scale(1);
  transition: transform 0.3s ease;
}

.sidebar-item:hover .cart-count {
  transform: scale(1.1);
  background: #ff4949;
}

/* 修改反馈对话框样式 */
:deep(.el-dialog) {
  margin-top: 15vh !important;
}

:deep(.el-dialog__body) {
  padding: 20px 30px;
}

.feedback-uploader {
  :deep(.el-upload--picture-card) {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }
}

.customer-service-dialog {
  border-radius: 12px;
}

.customer-service-content {
  padding: 10px 0;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 15px;
  margin-bottom: 10px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.contact-item:hover {
  background: #f0f2f5;
  transform: translateY(-2px);
}

.contact-item i {
  font-size: 24px;
  margin-right: 15px;
  color: #409EFF;
}

.contact-item:nth-child(2) i {
  color: #67C23A;
}

.contact-item:nth-child(3) i {
  color: #E6A23C;
}

.contact-info {
  flex: 1;
}

.contact-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 4px;
}

.contact-value {
  font-size: 16px;
  color: #303133;
  font-weight: 500;
}

.copy-btn {
  padding: 6px 15px;
}

.service-time {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #EBEEF5;
  color: #909399;
  font-size: 13px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.service-time i {
  margin-right: 5px;
}

:deep(.el-dialog__header) {
  padding: 20px;
  border-bottom: 1px solid #EBEEF5;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 500;
}
</style> 